package com.cat.practice;

import java.util.HashMap;
import java.util.List;
/**
 * @author cat
 * @description https://leetcode.cn/problems/maximum-sum-of-almost-unique-subarray/
 * @create 2025/7/22 20:02
 * @since JDK17
 */

public class Solution01 {
    static HashMap<Integer, Integer> map = new HashMap<>();

    public long maxSum(List<Integer> nums, int m, int k) {
        int l = 0, cnt = 0, r = 0, n = nums.size(), num;
        long ans = 0, sum = 0;
        while (r < n) {
            num = nums.get(r);
            cnt = map.getOrDefault(num, 0); // 一共有多少个
            m -= cnt == 0 ? 1 : 0;
            sum += num;   // 加上当前的值
            map.put(num, cnt + 1);

            // 有k个数字了
            if (r - l + 1 == k) {
                if (m <= 0) {   // 至少m种不同的数字
                    ans = Math.max(sum, ans);
                }
                num = nums.get(l++);  //
                sum -= num;
                cnt = map.get(num);
                m += cnt == 1 ? 1 : 0;
                map.put(num, cnt - 1);
            }
            r++;
        }
        map.clear();
        return ans;
    }
}

